define(function (require, exports, module) {
    require("ie/ie-shim.js").init();
    var $ = require('jquery');
    require('jquery/jqueryui/jquery-ui.min.js');
    require('validate');
    require('cookie');
    require('jquery/placeholder.js');

    $.fn.placeholder();

    if (!window.i18n) {

        var i18nx = require("i18next");
        i18nx.init({
            lng: $.cookie("i18next") || "zh-CN",
            fallbackLng: false,
            load: 'current'
        }, function (t) {
            LoadContent();
        });
        window.i18n = i18nx;
    } else {
        LoadContent();
    }

    function LoadContent(){
        var errors=require("msmErrors");
        var utils = require('./utils.js');
        var lang = $.cookie('i18next');
        if(lang){
            if($("#langSelect")[0]){
                $("#langSelect").find('option:selected')[0].selected = false;
                $("#langSelect").find('option[value="'+ lang +'"]')[0].selected = true;
            }
        }
        //切换语言
        $("#langSelect").on("change",function(){
            i18n.setLng($(this).val());
            location.reload();
        });
        /*注册渠道*/
        var uzchannel = location.search.split('uzchannel=')[1] || '';
        if (uzchannel) {
            $.cookie('uzchannel',uzchannel);
        };
        //首页蹦过来直接体验
        var urlSearch = location.search.slice(1);
        urlSearch = decodeURIComponent(urlSearch);
        urlSearch = urlSearch.split('&');
        var i = 0, len = urlSearch.length;
        var temp, tempArr, usrInput, emailInput;
        for(i; i<len; i++){
            temp = urlSearch[i];
            tempArr = temp.split('=');
            if(tempArr[0] === 'user'){
                usrInput = tempArr[1];
            }
            if(tempArr[0] === 'email'){
                emailInput = tempArr[1];
            }
            if(usrInput){
                $('#regNickname').val(usrInput);
            }
            if(emailInput){
                $('#regUserName').val(emailInput);
            }

        }
        // 验证码部分
        var changeCcap = function(){
            $('.ccap').attr('src', '/getccap?'+(Math.random()+'').replace('.',''));
        };
        $('.ccap').on('click', function(event) {
            changeCcap();
            event.preventDefault();
        });
        changeCcap();
        // 验证码部分 end
        
        var signup = function(type){
            // /api/user/signup
            // email - email
            // name - 名称（昵称）
            // inviteCode - 邀请码
            // captcha - 验证码
            $('#submit').attr('disabled', 'disabled');
            var email = $('#regUserName').val();
            var name = $('#regNickname').val();
            var phoneCode = $('#codePhoneText').val();
            var password = $('#regPwd').val();
            var phone = $('#codePhoneNum').val();
            var captcha = $('#ccap-text').val();
            var randomPwd = parseInt(Math.random()*10000000+1)+''+new Date().getTime();
            var url = '';
            var data = {};

            if (type) {
                url = '/api/v2/user/signup';
                data = {
                    email: email,
                    name: name,
                    password: password,
                    phone: phone,
                    phoneCode: phoneCode
                };
            } else{
                url = '/api/user/signup';
                data = {
                    email: email,
                    name: name,
                    password: password,
                    phone: phoneNumTemp
                };
            }
            
                
            // 
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'JSON',
                data: data
            })
            .done(function(data) {
                if (data && data.status) {
                    var bbsFrm = $('#bbsLogin')[0].contentWindow.document.getElementById('bbsFrm');
                    var $usr = $(bbsFrm).find('[name="username"]');
                    var $pwd = $(bbsFrm).find('[name="pwd"]');
                    $usr.val(email);
                    if (type) {
                        $pwd.val(password);
                    } else{
                        $pwd.val(password);
                    }
                    
                    bbsFrm.submit();
                    var $tongji_baidu = $('#tongji_baidu');
                    $tongji_baidu.attr('src', '/tongji_baidu/baidutongji.html');
                    $.cookie('username',email,{ expires: 7 });
                    $.cookie('ifIntGuide','true',{ expires: 7 });
                    setTimeout(function(){
                        // 注册成功跳转到激活页面
                        if (type) {
                            window.location.href = '/console';
                        } else{
                            window.location.href = '/signup-activation';
                        }
                    },2000);
                } else{
                    utils.alertMessage(0,errors.msmTip[data.code]);
                }
            })
            .fail(function() {
                console.log("signup ajax error");
            })
            .always(function() {
                $('#submit').removeAttr('disabled');
            });
            
            // 
            // var inviteCode = $('#inviteCode').val();
            // var captcha = $('#ccap-text').val();
            // var randomPwd = parseInt(Math.random()*10000000+1)+''+new Date().getTime();
            // $.ajax({
            //     url: '/api/user/signup?mobile=1', //免邀请码
            //     type: 'POST',
            //     dataType: 'json',
            //     data: {
            //         email: email,
            //         name: name,
            //         password: password,

            //         // inviteCode: inviteCode,
            //         // password: randomPwd,
            //         // captcha: captcha
            //     }
            // })
            // .done(function(data) {
            //     if (data.status == 1) {
            //         //BBS login
            //         var bbsFrm = $('#bbsLogin')[0].contentWindow.document.getElementById('bbsFrm');
            //         var $usr = $(bbsFrm).find('[name="username"]');
            //         var $pwd = $(bbsFrm).find('[name="pwd"]');
            //         $usr.val(email);
            //         $pwd.val(randomPwd);
            //         bbsFrm.submit();
                    
            //         $.cookie('username',email,{ expires: 7 });
            //         $.cookie('ifIntGuide','true',{ expires: 7 });
            //         setTimeout(function(){
            //              // 注册成功跳转到激活页面
            //             window.location.href = '/signup-activation';
            //             // window.location.href = '/console';
            //         },2000);
            //     } else{
            //         utils.alertMessage(0,errors.msmTip[data.code]);
            //         changeCcap();
            //     }
            // })
            // .fail(function(data) {
            //     // console.log("error");
            // })
            // .always(function(data) {
            //     $('#submit').removeAttr('disabled');
            // });
            
        };
        //privacy service
        // $('#privacy').on('change', function(event) {
        //     if ($('#privacy').is(':checked')) {
        //         $('#submit').removeClass('nbg').removeAttr('disabled');
        //     } else {
        //         $('#submit').addClass('nbg').attr('disabled',true);
        //     }
        // });
        $('.labelForPro').on('click', '.fake-check2', function(event) {
            if ($('.labelForPro').hasClass('active')) {
                $('.labelForPro').removeClass('active')
                $('#submit').addClass('nbg').attr('disabled',true);
            } else{
                $('.labelForPro').addClass('active')
                $('#submit').removeClass('nbg').removeAttr('disabled');
            }
            event.preventDefault();
        });
        // $('#service').on('change', function(event) {
        //     if ($('#privacy').is(':checked') && $('#service').is(':checked')) {
        //         $('#submit').removeClass('nbg').removeAttr('disabled');
        //     } else {
        //         $('#submit').addClass('nbg').attr('disabled',true);
        //     }
        // });
        // 获取短信验证码部分
        var $codePhoneCount = $('#code_phone_count');
        var $codeText = $('#codeText');
        var $codePhoneNum = $('#codePhoneNum');
        function checkPhoneNum(){
            var result = false;
            var value = $codePhoneNum.val();
            $.ajax({
                url: '/api/user/phone/check',
                type: 'GET',
                cache: false,
                dataType: 'json',
                data: {phone: value},
                async: false,
                success: function(data){
                    if (data.status == 1) {
                        if(data.result.count == 0){
                            result = true;
                        } else {
                        }  
                    } else{
                    }
                }
            });
            return result;
        };
        function showEmailNotice(){
            $('#go_email_modal').dialog({
                dialogClass: 'go_email_modal',
                resizable: false,
                minHeight: 220,
                minWidth: 500,
                modal: true,
                close: function(){
                    
                }
            });

            setTimeout(function(){
                $('#go_email_modal').dialog('close');
                changeForm();
            },1000);
        };

        var getcodeTimer;
        function getPhoneCodeStatus(){
            if (getcodeTimer) {

            } else{
                getcodeTimer = setInterval(function(){
                    $.ajax({
                        url: '/api/phone/message/status',
                        dataType: 'json',
                        cache: false
                    })
                    .done(function(data) {
                        if (data && data.status) {
                            var state = data.result.state;
                            var times = data.result.times;
                            if(state == null){
                                
                            } else if (state == 0){
                                clearInterval(getcodeTimer);
                                getcodeTimer = null;
                            } else{
                                clearInterval(getcodeTimer);
                                getcodeTimer = null;
                                // resetGetBtn();
                                // if (times == 1) {
                                //     utils.alertMessage(0, i18n.t("common.signupTips1"));
                                // }
                                if (times >= 2) {
                                    utils.alertMessage(0, i18n.t("common.signupTips"));
                                    changeForm();
                                }
                            }
                        } else{

                        }
                    })
                    .fail(function() {
                    })
                    .always(function() {
                    });
                    
                },1000);
            }
        };
        // 
        function resetGetBtn(){
            $('.code-phone-btn').removeAttr('disabled');
            $codeText.html(i18n.t('profile.info1_8'));
            clearInterval(thisTimer);
        };
        var phoneNumTemp;
        var thisTimer;
        var requestCount = 0;
        $('.code-phone-btn').on('click', function(event) {
            var $this = $(this);
            $this.attr('disabled', true);
            
            $codePhoneCount.html('');
            $codeText.html(i18n.t('error.A00013'));
            var thisTimeCount = 90;
            var phoneNum = $codePhoneNum.val();
            var reg = /^1[3|4|5|7|8][0-9]\d{8}$/g;

            if (phoneNum == '') {
                // 为空时候，不能获取验证码
                var errorStr = '<label for="codePhoneNum" class="error">'+i18n.t('error.A00012')+'</label>'
                $codePhoneNum.addClass('error');
                $('.forCodePhone .err-popover').addClass('active');
                $('.forCode-phone-num').html(errorStr);
                $this.removeAttr('disabled');
                return;
            }
            if (!reg.test(phoneNum)) {
                // 格式不对，不能获取验证码
                var errorStr = '<label for="codePhoneNum" class="error">'+i18n.t('error.A000028')+'</label>'
                $codePhoneNum.addClass('error');
                $('.forCodePhone .err-popover').addClass('active');
                $('.forCode-phone-num').html(errorStr);
                $this.removeAttr('disabled');
                return;
            }
            if (!checkPhoneNum()) {
                var errorStr = '<label for="codePhoneNum" class="error">'+i18n.t('error.A000029')+'</label>'
                $codePhoneNum.addClass('error');
                $('.forCodePhone .err-popover').addClass('active');
                $('.forCode-phone-num').html(errorStr);
                $this.removeAttr('disabled');
                return;
            }
            phoneNumTemp = phoneNum;
            $.ajax({
                url: '/api/user/signup/phone/code',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    phone: phoneNum
                }
            })
            .done(function(data) {
                if (data && data.status) {
                    // getPhoneCodeStatus();
                    requestCount++;
                    thisTimeCount = parseInt(data.result.remain);
                    $codePhoneCount.html(thisTimeCount);
                    $codeText.html(i18n.t('common.remains'));
                    thisTimer = setInterval(function(){
                        thisTimeCount--;
                        $codePhoneCount.html(thisTimeCount);
                        if (thisTimeCount <= 0) {
                            resetGetBtn();
                            if (requestCount >= 2) {
                                changeForm();
                            }
                        }
                    },1000);
                } else{
                    utils.alertMessage(0, errors.msmTip[data.code]);
                    $this.removeAttr('disabled');
                }
            })
            .fail(function() {
                // utils.alertMessage(0, data.);
                $this.removeAttr('disabled');
            })
            .always(function() {
            });

            event.preventDefault();
        });

        // 改变表单结构
        function changeForm(){
            var thisForm = $('#regForm');
            // thisForm.find('#regPwd').parents('.form-group').remove();
            // thisForm.find('#codePhoneNum').parents('.form-group').remove();
            thisForm.find('#codePhoneNum').attr('disabled','disabled');
            thisForm.find('#codePhoneText').parents('.form-group').remove();
            $('.emailnotes').show();
            // thisForm.find('#ccap-text').parents('.form-group').show();
        };
        // changeForm();
        //表单验证
        $.validator.addMethod("maxCNrange",function(value, element,param) {
            var cArr = value.match(/[^\x00-\xff]/ig);
            var len= value.length + (cArr == null ? 0 : cArr.length);
            if(len>=param[0]&&len<=param[1]){
                return true;
            }
            return false;
        }, i18n.t('error.A000018'));
        $.validator.addMethod("maxCNLen", function (value, element, param) {
            var cArr = value.match(/[^\x00-\xff]/ig);
            var len = value.length + (cArr == null ? 0 : cArr.length);
            return len <= param;
        }, i18n.t('member.notice2'));
        $.validator.addMethod("ajaxNameCheck", function (value, element, param) {
            var regTrim = /\s/g;
            var $this = $(element);
            $this.val($this.val().replace(regTrim,''));
            value = value.replace(regTrim, '');

            // 可用remote
            var result = false;
            $.ajax({
                url: '/api/user/email/check',
                type: 'GET',
                cache: false,
                dataType: 'json',
                data: {email: value},
                async: false,
                success: function(data){
                    if (data.status == 1) {
                        if(data.result.count == 0){
                            result = true;
                        } else {
                        }  
                    } else{
                    }
                },
                error: function(data){
                }
            });
            return result;
        }, i18n.t('appInfo.notice7'));
        $.validator.addMethod("ajaxPhoneCheck", function (value, element, param) {
            // 可用remote
            var regTrim = /\s/g;
            var $this = $(element);
            $this.val($this.val().replace(regTrim,''));
            value = value.replace(regTrim, '');

            var result = false;
            $.ajax({
                url: '/api/user/phone/check',
                type: 'GET',
                cache: false,
                dataType: 'json',
                data: {phone: value},
                async: false,
                success: function(data){
                    if (data.status == 1) {
                        if(data.result.count == 0){
                            result = true;
                        } else {
                        }  
                    } else{
                    }
                },
                error: function(data){
                }
            });
            return result;
        }, i18n.t('error.A000029'));
        $.validator.addMethod("checkForGmail", function (value, element, param) {
            // gmail 临时
            var result = false;
            var str = /@gmail.com$/;
            if (str.test(value)) {
                result = false;
            } else {
                result = true;
            }
            return result;
        }, i18n.t('appInfo.notice8'));

        $.validator.addMethod("checkMail", function (value, element, param) {
            var result = false;
            var regTrim = /\s/g;
            var $this = $(element);
            $this.val($this.val().replace(regTrim,''));
            value = value.replace(regTrim, '');
            // var reg = /@[0-9a-zA-Z_-]+(\.[0-9a-zA-Z_-]+)+$/;
            var reg = /^[A-Za-z\d]+([\-\.\w]+)*@([A-Za-z\d]+[\-\.])+[A-Za-z\d]{2,5}$/;
            if (!reg.test(value)) {
                result = false;
            } else {
                result = true;
            }
            return result;
        }, i18n.t('appInfo.notice11'));

        $.validator.addMethod("checkPhone", function (value, element, param) {
            var result = false;
            var reg = /^1[3|4|5|7|8][0-9]\d{8}$/g;
            var regTrim = /\s/g;
            var $this = $(element);
            $this.val($this.val().replace(regTrim,''));
            value = value.replace(regTrim, '');
            if (!reg.test(value)) {
                result = false;
            } else {
                result = true;
            }
            return result;
        }, i18n.t('error.A000028'));
        
        $.validator.addMethod("ajaxNicknameCheck", function (value, element, param) {
            var result = false;
            $.ajax({
                url: '/api/user/name/check',
                type: 'GET',
                cache: false,
                dataType: 'json',
                data: {name: value},
                async: false,
                success: function(data){
                    if (data.status == 1) {
                        if(data.result.count == 0){
                            result = true;
                        } else {
                        }  
                    } else{
                    }
                },
                error: function(data){
                    // console.log(data);
                }
            });
            return result;
        }, i18n.t('appInfo.notice9'));

        $('#regForm').validate({
            onkeyup: false,
            errorPlacement: function (error, element) {
                $(element).parents('.form-group').find('.err-popover-content').html(error);
            },
            rules: {
                regUserName: {
                    required: true,
                    // checkForGmail: true,
                    checkMail: true,
                    // email: true,
                    ajaxNameCheck: true
                },
                regNickname: {
                    required: true,
                    maxCNrange: [4,24],
                    ajaxNicknameCheck: true
                },
                regPwd: {
                    required: true,
                    maxCNrange: [6,16]
                },
                
                // inviteCode: {
                //     required: true
                // },
                ccap: {
                    required: true
                },
                codePhoneNum: {
                    required: true,
                    checkPhone: true,
                    ajaxPhoneCheck: true
                },
                codePhoneText: {
                    required: true
                }
            },
            messages: {
                regUserName: {
                    required: i18n.t('appInfo.notice10'),
                    checkMail: i18n.t('appInfo.notice11'),
                    // email: i18n.t('appInfo.notice11')
                },
                regNickname: {
                    required: i18n.t('appInfo.notice12')
                },
                // inviteCode: {
                //     required: i18n.t('appInfo.notice13')
                // },
                ccap: {
                    required: i18n.t('appInfo.notice14')
                },
                regPwd: {
                    required: i18n.t('member.notice3'),
                    maxCNrange: i18n.t('error.A00006')
                },
                codePhoneNum: {
                    required: i18n.t('error.A00012'),
                    checkPhone: i18n.t('error.A000028'),
                    ajaxPhoneCheck: i18n.t('error.A000029')
                },
                codePhoneText: {
                    required: i18n.t('appInfo.inputPhoneCode')
                }
            },
            highlight: function(element, errorClass){
                $(element).addClass('error');
                $(element).parents('.form-group').find('.err-popover').addClass('active');
            },
            unhighlight: function(element, errorClass){
                $(element).removeClass('error');
                $(element).parents('.form-group').find('.err-popover').removeClass('active');
            },
            submitHandler: function(form) {
                // 验证码
                var value = $('#ccap-text').val();
                var result = 0;
                signup($('#codePhoneText').length);
                return false;
                
                $.ajax({
                    url: '/checkccap',
                    type: 'POST',
                    data: {
                        'validCode': value
                    },
                    async: true,
                    success: function(data){
                        var data = eval('('+data+')');
                        if (data.status == 1){
                            $('#ccap-text').removeClass('error');
                            $('#ccap-text').parents('.form-group').find('.err-popover').removeClass('active');
                            $('#submit').attr('disabled', 'disabled');
                            signup();

                        } else {
                            changeCcap();
                            $('#ccap-text').addClass('error');
                            $('#ccap-text').parents('.form-group').find('.err-popover').addClass('active');
                            $('#ccap-text').parents('.form-group').find('.err-popover-content').html('<label class="error">'+ i18n.t('appInfo.notice15') +'</label>');
                            return;
                        }
                    }
                });
                // 验证码 end

                return false;
            }
        });

        //apply code
        var $applyMark = $('#apply-dia-mark');
        var $applyDia = $('#apply-dialog');
        var $apply = $('#applyCode');
        var $applyBtn = $applyDia.find('.apply');
        var $cancelBtn = $applyDia.find('.cancel');

        $apply.on('click',function(){
            $applyDia.find('.email').val("");
            $applyDia.find('.idea').val("");
            $applyMark.show();
            $applyDia.show();
        });
        $cancelBtn.on('click',function(){
            $applyMark.hide();
            $applyDia.hide();
        });
        $applyBtn.on('click',function(){
            var email = $applyDia.find('.email').val();
            var idea = $applyDia.find('.idea').val();
            var reg = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
            if(!reg.test(email)){
                utils.alertMessage(0, i18n.t('appInfo.notice16'));
                return false;
            }
            $.post('/api/user/inviteCode/apply', {
                email: email,
                message: idea
            }, function(data) {
                if(data.status){
                    utils.alertMessage(1, i18n.t('appInfo.notice17'));
                }else{
                    utils.alertMessage(0,errors.msmTip[data.code]);
                }
                $applyMark.hide();
                $applyDia.hide();
            });
            
        });
        
    }
    exports.init = function(){};
    

});
